<template>
  <div class="trace-container">
    <!-- 高级搜索区域 -->
    <div>
      <el-card shadow="hover">
        <div class="search-header">
          <h3>联邦学习任务追溯</h3>
          <el-divider content-position="left"><i class="el-icon-search"></i></el-divider>
        </div>

        <el-form :inline="true" class="search-form">
          <el-form-item label="任务ID">
            <el-input v-model="searchParams.taskId" placeholder="请输入任务ID" clearable prefix-icon="el-icon-document">
            </el-input>
          </el-form-item>

          <el-form-item label="时间范围">
            <el-date-picker v-model="searchParams.dateRange" type="daterange" range-separator="-"
              start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd">
            </el-date-picker>
          </el-form-item>

          <!-- <el-form-item label="参与方">
            <el-select v-model="searchParams.participants" multiple collapse-tags placeholder="选择参与节点">
              <el-option v-for="node in nodeOptions" :key="node.id" :label="node.name" :value="node.id">
              </el-option>
            </el-select>
          </el-form-item> -->

          <el-form-item style="margin-left: 20px;">
            <el-button type="primary" icon="el-icon-search" @click="handleSearch">
              追溯查询
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>

    <!-- 可视化溯源结果 -->
    <el-card shadow="never" class="result-card">
      <div class="result-header">
        <h4>溯源结果（共 {{ total }} 条记录）</h4>
      </div>
      <el-table :data="tableData" stripe style="width: 100%" v-loading="loading" element-loading-text="区块链数据加载中..."
        :default-sort="{  order: 'descending' }">
        <!-- 任务信息列 -->
        <el-table-column label="任务名称" min-width="150" :resizable="false">
          <template v-slot="{ row }">
            <div class="task-info">
              <el-tag effect="dark" :type="statusMap[row.status].type" size="mini">
                {{ statusMap[row.status].label }}
              </el-tag>
              <div class="task-name">{{ row.taskName }}</div>
              <!-- <div class="task-id">ID: FL-{{ row.taskId.slice(0, 8) }}</div> -->
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="taskID" min-width="90"  label="任务ID" show-overflow-tooltip header-align="center" align="center"  ></el-table-column>

        <!-- 参与方列 -->
        <el-table-column label="参与节点" min-width="90" header-align="center" align="center"  >
          <template v-slot="{ row }">
            <el-popover placement="right" width="300" trigger="hover">
              <div class="participant-list">
                <div v-for="(node, index) in row.participants" :key="index" class="participant-item">
                  <i class="el-icon-cpu"></i>
                  <span>{{ node.name }}</span>
                  <el-tag size="mini">{{ node.type }}</el-tag>
                </div>
              </div>
              <template #reference>
                <div class="participant-brief">
                  <!-- <el-avatar :size="30" :src="nodeAvatar(row.participants.length)"></el-avatar> -->
                  <span class="count">{{ row.participants.length }} </span>
                </div>
              </template>
            </el-popover>
          </template>
        </el-table-column>

        <!-- 区块链信息列（弹性宽度） -->
        <el-table-column label="链上记录"  min-width="600" header-align="left" align="left" sortable >
          <template v-slot="{ row }">
            <div class="blockchain-record">
              <div class="hash-row">
                <i class="el-icon-link hash-icon"></i>
                <div class="full-hash">
                  <p type="primary" :underline="false" class="hash-link">
                    {{ row.blockHash }}
                  </p>
                  <el-button size="mini" icon="el-icon-document-copy" class="copy-btn"
                    @click="copyHash(row.blockHash)">复制</el-button>
                </div>
              </div>
              <div class="meta-row">

                <span class="meta-item">
                  <i class="el-icon-time"></i>
                  时间：2024-06-24 17:41:32
                </span>
              </div>
            </div>
          </template>
        </el-table-column>

        <!-- 训练指标列 -->
        <el-table-column label="训练指标" width="180" :resizable="false">
          <template v-slot="{ row }">
            <div class="metrics">
              <div class="metric-item">
                <span class="label">测试准确率：{{ row.accuracy }}%</span>
                <el-progress  :percentage="row.accuracy" :color="accuracyColor(row.accuracy)" :show-text="false"
                  stroke-width="8" />
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="80" align="center">
          <template v-slot="scope">
            <el-button plain type="primary" @click="handleEdit(scope.row)" size="mini">详情</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination class="pagination" background layout="prev, pager, next, jumper" :current-page="currentPage"
        :page-size="pageSize" :total="total" @current-change="handlePageChange" />
    </el-card>
  </div>
</template>

<script>
import dayjs from 'dayjs'

const mockTraceData = [
  {
    taskId: 'fba73e8c-711d-4d8c',
    taskName: '联邦任务CNN模型训练        （EMNIST、IID）',
    status: 'success',
    taskID:37,
    participants: [
      { name: '协和医院节点', type: '医院' },
      { name: '301医院节点', type: '医院' },
      { name: '301医院节点', type: '医院' },
      { name: '301医院节点', type: '医院' },
      { name: '301医院节点', type: '医院' },
      { name: '301医院节点', type: '医院' },
      { name: '301医院节点', type: '医院' },
      { name: '301医院节点', type: '医院' },
      { name: '301医院节点', type: '医院' },
      { name: '301医院节点', type: '医院' },
      { name: '301医院节点', type: '医院' },
      { name: '301医院节点', type: '医院' },
      { name: '301医院节点', type: '医院' },
      { name: '301医院节点', type: '医院' },
      { name: '301医院节点', type: '医院' },
    ],
    blockHash: '0x4f87dba3f5aa28b33c89ed379d8eba7ff0b2a2bd760eb225b81cdc564d7fda93',
    blockHeight: 123456,
    timestamp: 1711456307,
    accuracy: 87.53,
    loss: 12.65
  },
]

export default {
  data() {
    return {
      searchParams: {
        taskId: '',
        dateRange: [],
        participants: []
      },
      tableData: [],
      total: 0,
      currentPage: 1,
      pageSize: 10,
      loading: false,
      statusMap: {
        success: { label: '已完成', type: 'success' },
        running: { label: '进行中', type: 'primary' },
        failed: { label: '已终止', type: 'danger' }
      },
      nodeOptions: [
        { id: 'node1', name: '医疗节点-01', type: '医院' },
        { id: 'node2', name: '金融节点-02', type: '银行' },
        { id: 'node3', name: '科研节点-03', type: '实验室' }
      ]
    }
  },

  created() {
    this.loadData()
    this.latestBlock = Math.max(...mockTraceData.map(d => d.blockHeight))
  },

  methods: {
    async loadData() {
      this.loading = true
      // 模拟异步请求
      setTimeout(() => {
        this.tableData = mockTraceData
          .slice((this.currentPage - 1) * this.pageSize, this.currentPage * this.pageSize)
        this.total = mockTraceData.length
        this.loading = false
      }, 800)
    },
    handleSearch() {
      this.currentPage = 1
      this.loadData()
    },

    handlePageChange(page) {
      this.currentPage = page
      this.loadData()
    },
    copyHash(hash) {
      const textarea = document.createElement('textarea')
      textarea.value = hash
      textarea.style.position = 'fixed'
      document.body.appendChild(textarea)

      try {
        // 现代浏览器方案
        if (navigator.clipboard) {
          navigator.clipboard.writeText(hash).then(() => {
            this.$message.success('哈希已复制')
          }).catch(err => {
            throw new Error('安全限制阻止复制')
          })
        }
        // 兼容性方案
        else if (document.execCommand('copy')) {
          textarea.select()
          const success = document.execCommand('copy')
          if (!success) throw new Error('复制命令失败')
          this.$message.success('哈希已复制')
        }
      } catch (err) {
        console.error('复制失败:', err)
        this.$message.error(`复制失败: ${err.message}`)
      } finally {
        document.body.removeChild(textarea)
      }
    },
    nodeAvatar(count) {
      const avatars = [
        require('@/assets/node1.png'),
        require('@/assets/node2.png'),
        require('@/assets/node3.png')
      ]
      return avatars[count % 3]
    },
    accuracyColor(val) {
      if (val >= 90) return '#67C23A'
      if (val >= 75) return '#E6A23C'
      return '#F56C6C'
    },
    formatFullTime(timestamp) {
      return dayjs(timestamp).format('YYYY-MM-DD HH:mm:ss')
    },
  }
}
</script>

<style lang="scss" scoped>
.trace-container {
  padding: 10px;
  background: #f5f7fa;

  .blockchain-record {
    padding: 8px 0;
    min-width: 480px;

    .hash-row {
      display: flex;
      align-items: center;
      margin-bottom: 6px;

      .hash-icon {
        color: #409EFF;
        font-size: 18px;
        margin-right: 10px;
        flex-shrink: 0;
      }

      .full-hash {
        flex: 1;
        display: flex;
        align-items: center;
        overflow-x: auto;

        .hash-link {
          font-family: Monaco, Consolas, monospace;
          font-size: 14px;
          white-space: nowrap;
          max-width: none;
          overflow: visible;

          &::-webkit-scrollbar {
            height: 3px;
          }
        }

        .copy-btn {
          margin-left: 12px;
          padding: 5px 10px;
          font-size: 12px;
          flex-shrink: 0;
        }
      }
    }

    .meta-row {
      display: flex;
      align-items: center;
      font-size: 12px;
      color: #606266;

      .meta-item {
        display: inline-flex;
        align-items: center;

        i {
          margin-right: 4px;
          font-size: 14px;
        }

        &:first-child {
          color: #67C23A;

          i {
            color: #67C23A;
          }
        }
      }

      .el-divider {
        margin: 0 12px;
        background-color: #dcdfe6;
      }
    }
  }

  @media (max-width: 1600px) {
    .hash-link {
      max-width: none !important;
    }

    .copy-btn {
      display: inline-flex !important;
    }
  }
}
</style>
